import { connection } from '../app/database/mysql';
import { geByIdtMovieCategory, getIdCountry } from '../category/category.service';
import { getUserById } from '../user/user.service';
import { getVideoUrlWai } from '../videoPlay/videoPlay.service';
import { newMovieModel } from './newMovie.model';

/**
 * 获取内容
 */
export const getNewMovie = async (pageNo: number, pageSize: number, status: number) => {
  // 准备查询
  let statement = `
    SELECT SQL_CALC_FOUND_ROWS *, COUNT(id) OVER () AS total FROM new_movie
  `;
  let where = []
  if (status > 0) {
    where.push(`status = ` + status)
  }
  if (where.length > 0) {
    statement += ` where `
    for (let i = 0; i < where.length; i++) {
      statement += where[i]
      if (i < where.length - 1) {
        statement += ` and `
      }
    }
  }
  
  statement += ` ORDER by id DESC, id DESC limit ` + (pageNo > 0 ? (pageNo - 1) * pageSize : 0) + `,` + pageSize
  
  // 执行查询
  const [data] = await connection.promise().query(statement);

  let totalCount: any;
  if (data[0] && data[0].total) totalCount = data[0].total;
  let totalPage = (totalCount % pageSize) > 0 ? parseInt(`${totalCount / pageSize}`) + 1 : totalCount / pageSize

  for (let i of data as any) {
    if (i.category && i.category.length > 0) {
      let category_arr = [];
      for (let e of i.category.match(/\d+/g)) {
        let category_dan = await geByIdtMovieCategory(e)
        category_arr.push(category_dan);
      }
      i.category = category_arr;
    }

    if (i.country && i.country.length > 0) {
      let country_arr = [];
      for (let e of i.country.match(/\d+/g)) {
        let country_dan = await getIdCountry(e)
        country_arr.push(country_dan);
      }
      i.country = country_arr;
    }

    // i.videoUrl = await getVideoUrlWai(i.url);
  }

  // 提供数据
  let res = {
    data,
    totalPage,
    totalCount
  }
  // 提供数据
  return res;
};

/**
 * 按 ID 获取内容
 */
export const getIdNewMovie = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM new_movie
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data;
}


/**
 * 创建内容
 */
export const createNewMovie = async (post: newMovieModel) => {
  // 准备查询
  const statement = `
    INSERT INTO new_movie
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, post);

  // 提供数据
  return data;
}

/**
 * 删除内容
 */
export const deleteNewMovie = async (postId: number) => {
  // 准备查询
  const statement = `
    DELETE FROM new_movie
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data;
}

/**
 * 更新内容
 */
export const updateNewMovie = async (post: newMovieModel, postId: number) => {
  // 准备查询
  const statement = `
    UPDATE new_movie
    SET ?
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data;
}
